<template>
	<view class="document">
		<el-collapse v-model="activeNames">
			<el-collapse-item class="system" title="系统文件夹" name="1">
				<view style=";display: flex;justify-content: flex-end;align-items: center;flex-wrap: wrap;">
					<view style="display: flex;">
						<el-button size="mini" v-if="Number(maxCount)>1" style="margin-right: 10px;"
							@click="multiples = !multiples">
							<view v-if="multiples">单选操作</view>
							<view v-else>多选操作</view>
						</el-button>
						<uv-search :disabled="!!(xilist[0]&&xilist[0].en)" placeholder="请输入搜索内容"
							v-model="system.keyword" @search="loadSystemList" @custom="loadSystemList"
							@clear="clearClick">
						</uv-search>
					</view>
				</view>
				<!-- 路径导航 -->
				<view class="path-nav">
					<view style="display: flex;justify-content: flex-start;">
						<text style="cursor: pointer;" v-for="(it, ind) in systemList" :key="it.name+ind"
							@click="skip(it)">
							{{ it.name }} /
						</text>
					</view>
				</view>
				<folder :disps="disps" v-model="value" :multiple="multiples" :maxCount="maxCount" :fileList="xilist"
					@handleItemClick="systemClick" @loadFileList="loadSystemList()"></folder>
				<el-pagination :hide-on-single-page="true" v-if="system.total>10" small layout="prev, pager, next"
					:page-size="system.pageSize" :total="system.total" @current-change="systemchange">
				</el-pagination>
			</el-collapse-item>
			<el-collapse-item title="自定义文件夹" name="2">
				<view style="padding: 0px 10rpx;">
					<view style="display: flex;justify-content: space-between;align-items: center;flex-wrap: wrap;">
						<view style="display: flex;justify-content: flex-start;align-items: center;flex-wrap: wrap;">
							<el-button v-if="!pathList[pathList.length-1].path.includes(folderStr)" size="small"
								@click="createNewFolder()" style="margin-right: 10px;">新建文件夹</el-button>
							<el-button v-if="!pathList[pathList.length-1].path.includes(folderStr)" size="small"
								@click="uploadFile" style="margin-right: 10px;">上传文件</el-button>
							<!-- <uv-button v-if="reitem[0]&&reitem[0].url" style="margin-right: 10px;"
							text="使用选中数据"></uv-button> ?.includes(folderStr)-->
							<el-button size="small"
								v-if="selectedItem&&selectedItem.id&&selectedItem.id!=currentParentId&&!pathList[pathList.length-1].path.includes(folderStr)"
								style="margin-right: 10px;" @click="confirmAction">粘贴</el-button>
						</view>
						<view style="display: flex;">
							<el-button size="small" v-if="Number(maxCount)>1" style="margin-right: 10px;"
								@click="multiple = !multiple">
								{{multiple?'单选操作':'多选操作'}}
							</el-button>
							<uv-search placeholder="请输入搜索内容" v-model="keyword" @search="loadFileList(currentParentId)"
								@custom="loadFileList(currentParentId)" @clear="clearClick">
							</uv-search>
						</view>
					</view>
					<view v-for="(item,index) in progress" :key="index">
						<view
							style="width: 100%;margin: 5px 0px;display: flex;justify-content: space-between;align-items: center;"
							v-if="item.progress>0">
							<uv-line-progress :percentage="item.progress" height="10"
								:activeColor="item.progress==100?'#3C9CFF':'#ff0000'"></uv-line-progress>
							<!-- <uv-button size="small" text="取消上传"></uv-button> -->
							<el-link v-if="item.uploadId && item.key" style="font-size: 12px;margin-left:10px;"
								@click="abortMultipartUpload(item.uploadId,item.key,index)">取消上传</el-link>
						</view>
					</view>


					<!-- 路径导航 -->
					<view class="path-nav">
						<view style="display: flex;justify-content: flex-start;">
							<text style="cursor: pointer;" v-for="(item, index) in pathList" :key="index"
								@click="jump(item)">
								<!-- <uv-text size="12" :text="cnName(item.name)"></uv-text> -->
								{{ cnName(item.name) }} /
							</text>
						</view>
						<view @click="clickTu">
							<uv-icon style="cursor: pointer;" size="21" name="grid"></uv-icon>
						</view>
					</view>
					<folder :disps="disps" v-model="value" :folderStr="folderStr" :multiple="multiple"
						:maxCount="maxCount" :fileList="fileList" @handleItemClick="handleItemClick"
						@handleClick="handleClick" @loadFileList="loadFileList(currentParentId)"></folder>
					<el-pagination :hide-on-single-page="true" v-if="fileList[0]" :page-size="custom.pageSize" small
						layout="prev, pager, next" :total="Number(custom.total)"
						@current-change="customchange"></el-pagination>
				</view>
			</el-collapse-item>
		</el-collapse>
		<view style="width: 0px;height: 0px;opacity: 0;">
			<uploadFile :cnName="cnName" :name="1" :mode="mode" :accept="accept" :uploadText="uploadText"
				:parentId="currentParentId" :width="95" :height="95" :maxCount="maxCount" ref="uploads"
				:fileList="imageUrl" @resdata="resdata" @toast="toast" @upload-progress="uploadProgress">
			</uploadFile>
		</view>
		<uv-toast ref="toast"></uv-toast>
	</view>
</template>

<script>
	import {
		getFileList,
		getScroll,
		createFolder,
		uploadFileName,
		moveItem,
		copyItem
	} from '@/common/api.js'; // 封装的后端API调用
	import config from '@/common/config'
	import folder from '@/components/folder/folder.vue';
	import uploadFile from '@/components/uploadFile/uploadFile.vue';
	export default {
		components: {
			// 注册组件
			folder,
			uploadFile
		},
		data() {
			return {
				tabbar: config.tabbar,
				currentPath: '/',
				currentParentId: null,
				pathList: [{
					name: '根目录',
					path: '/',
					id: null
				}],
				systemPath: '/',
				systemParentId: null,
				systemList: [{
					name: '根目录',
					url: '/',
					en: null
				}],
				weList: [],
				fileList: [],
				imageUrl: [],
				selectedItem: {},
				reitem: [],
				multiple: false,
				multiples: false,
				keyword: '',
				value: [],
				activeNames: ['2'],
				system: {
					keyword: '',
					total: 0,
					page: 1,
					pageSize: 10,
				},
				folderStr: '',
				custom: {
					total: 0,
					page: 1,
					pageSize: 10,
				},
				disps: 'list',
				progress: [],
			};
		},
		props: {
			// multiple: {
			// 	type: Boolean,
			// 	default: false,
			// },
			accept: {
				type: String,
				default: '',
			},
			uploadText: {
				type: String,
				default: ''
			},
			maxCount: {
				type: [Number, String],
			},
			mode: {
				type: String,
				default: null,
			},
			reset: {
				type: Boolean,
				default: false,
			},
		},
		watch: {
			// 监听data数据的变化
			// value(newVal, oldVal) {
			// 	console.log(newVal);
			// 	this.imageUrl = newVal;
			// },
			reset() {
				this.progress = [];
			},
		},
		// model: {
		// 	prop: 'value', // 对应 props 的属性名
		// 	event: 'input' // 触发事件名
		// },
		computed: {
			xilist() {
				let systemList = this.systemList;
				let en = systemList[systemList.length - 1].en
				if (!en) return this.tabbar;
				let index = this.tabbar.findIndex(ite => ite.en == systemList[systemList.length - 1].en);
				if (index >= 0) {
					return this.tabbar[index].children || this.weList;
				} else {
					return this.weList
				}
			},
		},
		onLoad(ee) {
			// 可选：从ee接收初始parentId
			if (ee && ee.parentId) {
				this.currentParentId = ee.parentId;
				this.loadFileList(this.currentParentId);
			} else {
				this.loadFileList(null); // 加载根目录
			}
			console.log('mounted');
		},
		methods: {
			abortMultipartUpload(uploadId, key, index) {
				return this.$refs.uploads.abortMultipartUpload(uploadId, key, index);
			},
			uploadProgress(i, e) {
				this.$set(this.progress, i, e);
				console.log(`${i} 上传进度: ${e.progress}%`);
			},
			clickTu() {
				this.disps = this.disps == 'list' ? 'icon' : 'list';
			},
			cnName(e) {
				let name = "";
				let mimeMap = {};
				mimeMap[this.folderStr] = '系统文件夹';
				if (mimeMap[e]) {
					name = mimeMap[e];
				}
				return name ? name : e;
			},
			clearClick() {
				this.clear();
				this.loadFileList(this.currentParentId);
			},
			clear() {
				this.currentPath = '/';
				this.currentParentId = null;
				this.pathList = [{
					name: '根目录',
					path: '/',
					id: null
				}];
				this.systemPath = '/';
				this.systemParentId = null;
				this.systemList = [{
					name: '根目录',
					path: '/',
					id: null
				}];
				this.weList = [];
				this.fileList = [];
				this.selectedItem = {};
				this.reitem = [];
				this.multiple = false;
				this.multiples = false;
				this.keyword = '';
				this.value = [];
				this.activeNames = ['2'];
				this.system = {
					keyword: '',
					total: 0,
					page: 1,
					pageSize: 10,
				};
				this.custom = {
					total: 0,
					page: 1,
					pageSize: 10,
				};
			},
			handleClick(e, clickType) {
				this.selectedItem = {
					id: e._id,
					type: clickType,
				}
			},
			toast(e) {
				this.$refs.toast.show(e);
			},
			async confirmAction() {
				if (!this.selectedItem) return;
				try {
					if (this.selectedItem.type === 'copy') {
						await copyItem({
							id: this.selectedItem.id,
							targetParentId: this.currentParentId
						}, {
							custom: {
								auth: true,
								toast: true,
								catch: true,
							},
						})
						this.toast({
							message: '复制成功'
						})
					} else if (this.selectedItem.type === 'paste') {
						await moveItem({
							id: this.selectedItem.id,
							targetParentId: this.currentParentId
						}, {
							custom: {
								auth: true,
								toast: true,
								catch: true,
							},
						});
						this.toast({
							message: '移动成功'
						})
					}

					this.selectedItem = {};
					this.loadFileList(this.currentParentId); // 刷新列表
				} catch (error) {
					this.toast({
						message: '操作失败：' + error.msg
					})
					console.error(`confirmAction:`, error);
				}
			},
			systemchange(e) {
				this.system.page = e;
				this.loadSystemList();
			},
			async loadSystemList() {
				uni.showLoading({
					title: '加载中'
				});
				try {
					let params = {
						sortBy: 'updatedAt',
						order: 'desc',
						list: true,
						total: this.system.total,
						page: this.system.page,
						pageSize: this.system.pageSize,
					}
					if (this.systemList[1]) params['type'] = this.systemList[1].en;
					if (this.systemList[2]) params['api'] = this.systemList[2].en;

					if (this.system.keyword) params['keyword'] = this.system.keyword;
					const res = await getScroll({
						custom: {
							auth: true,
							toast: false
						},
						params: params
					}); // 调用API
					let weList = [];
					this.system.total = res.total;
					let image = this.extractImageUrls(res.data);
					for (var index = 0; index < image.length; index++) {
						if (image[index].includes('http')) {
							const ext = image[index].split('.').pop().toLowerCase();
							var imgPath = image[index] + (ext == 'svg' ? '' :
								'?x-oss-process=image/resize,w_100,m_lfit')
							var imgUrl = image[index] + (ext == 'svg' ? '' :
								'?x-oss-process=image/resize,w_450,m_lfit')
							const img = new Image();
							img.src = imgPath;
							// 错误处理
							img.onerror = () => {
								console.error('图片预加载失败:');
								this.weList = this.weList.filter(item => item.on != index)
							}

							weList.push({
								name: '观止AI图片' + (index + 1),
								en: index + 1,
								icon: imgPath,
								path: 'ccc',
								url: imgUrl,
							});
						}
					}
					// console.log('weList', weList);
					this.weList = weList;
					uni.hideLoading();
				} catch (error) {
					uni.hideLoading();
					this.$refs.toast.show({
						message: '加载失败',
						icon: 'error'
					})
					console.error('Load file list error:', error);
				}
			},
			// 主函数：从任意结构中提取图片 URL
			extractImageUrls(data) {
				var that = this;
				const results = new Set(); // 使用 Set 自动去重
				const visited = new WeakSet(); // 防止循环引用
				// 递归遍历函数
				function traverse(obj) {
					if (!obj || visited.has(obj)) return;
					// 标记已访问对象（避免循环引用）
					if (typeof obj === 'object' && obj !== null) {
						visited.add(obj);
					}
					// 处理字符串（核心匹配逻辑）
					if (typeof obj === 'string') {
						if (that.isImageUrl(obj)) {
							results.add(obj);
						}
						return;
					}
					// 处理数组
					if (Array.isArray(obj)) {
						obj.forEach(itm => traverse(itm));
						return;
					}
					// 处理对象
					if (typeof obj === 'object') {
						Object.values(obj).forEach(itm => traverse(itm));
					}
				}
				traverse(data);
				return Array.from(results); // 转为数组返回
			},
			// 判断字符串是否为图片 URL
			isImageUrl(str) {
				// 匹配图片扩展名 // 匹配完整图片 URL // 匹配 base64 图片
				return /\.(jpe?g|png|gif|bmp|webp|svg)(\?[^\\s]*)?$/i.test(str) ||
					/^(https?:\/\/.*\.(?:png|jpg|jpeg|gif|webp))/i.test(str) ||
					/^data:image\/([a-zA-Z]*);base64,/.test(
						str);
			},
			customchange(e) {
				this.custom.page = e;
				this.loadFileList(null);
			},
			async loadFileList(parentId) {
				uni.showLoading({
					title: '加载中'
				});
				try {
					let params = {
						sortBy: 'updatedAt',
						order: 'desc',
						total: this.custom.total,
						page: this.custom.page,
						pageSize: this.custom.pageSize,
					}
					if (parentId) params['parentId'] = parentId;
					if (this.keyword) params['keyword'] = this.keyword;
					if (this.accept) params['accept'] = this.accept;
					const res = await getFileList('list', {
						custom: {
							auth: true,
							toast: false
						},
						params: params
					}); // 调用API
					this.custom.total = res.total;
					this.fileList = res.data;
					this.folderStr = res.folderStr;
					uni.hideLoading();
				} catch (error) {
					uni.hideLoading();
					this.$refs.toast.show({
						message: '加载失败',
						icon: 'error'
					})
					console.error('Load file list error:', error);
				}
			},
			handleItemClick(item) {
				if (this.multiple) {
					let index = this.value.findIndex(ite => ite._id == item._id);
					if (index >= 0) {
						if (this.value.length >= this.maxCount) return;
						this.value.splice(index, 1);
					} else {
						this.value.push(item);
					}
				} else {
					if (item.kind === 'Folder') {
						// 或者更新当前页面的pathList和fileList
						this.pathList.push({
							name: item.name,
							path: item.path,
							id: item._id
						});
						this.currentParentId = item._id;
						this.loadFileList(this.currentParentId);
					} else {
						this.value = [item];
					}
				}
				// console.log(this.value);
				this.$emit('selected', this.value);
				return
			},
			async createNewFolder() {
				const originalShowModal = uni.showModal;
				Object.defineProperty(uni, "showModal", {
					get() {
						return (options) => {
							const element = document.querySelector("uni-modal");
							if (element) {
								element.style.zIndex = "20000";
							}
							return originalShowModal(options);
						};
					},
				});
				uni.showModal({
					title: '新建文件夹',
					content: '',
					editable: true,
					placeholderText: '请输入文件夹名称',
					success: async (res) => {
						if (res.confirm) {
							const folderName = res.content;
							if (!folderName) {
								this.$refs.toast.show({
									message: '名称不能为空',
									icon: 'error'
								})
								return;
							}
							try {
								await createFolder({
									name: folderName,
									parent: this.currentParentId
								}, {
									custom: {
										auth: true,
										toast: false,
										catch: true,
									},
								});
								this.$refs.toast.show({
									message: '创建成功'
								})
								this.loadFileList(this.currentParentId); // 刷新列表
							} catch (error) {
								this.$refs.toast.show({
									message: '创建失败: ' + error.msg,
									icon: 'error'
								})
								console.error('Create folder error:', error);
							}
						}
					}
				});
			},
			resdata() {
				this.loadFileList(this.currentParentId); // 刷新列表
			},
			uploadFile() {
				this.$refs.uploads.handleClick()
				return;
			},
			skip(pathInfo) {
				// 处理路径导航点击，跳转到指定路径
				// 需要实现根据pathInfo.id或pathInfo.path加载对应目录
				this.systemParentId = pathInfo.en;
				// 更新pathList，截断到点击的位置
				const index = this.systemList.findIndex(item => item.en == pathInfo.en);
				if (index !== -1) {
					this.systemList = this.systemList.slice(0, index + 1);
				}
				this.system = {
					total: 0,
					page: 1,
					pageSize: 10,
				};
				if (this.systemParentId) {
					this.loadSystemList();
				} else {
					this.weList = [];
				}
			},
			systemClick(item) {
				if (item.en) {
					// 或者更新当前页面的pathList和fileList
					this.systemList.push({
						name: item.name,
						url: item.url,
						en: item.en
					});
					this.systemParentId = item.en;
					if (!this.xilist[this.xilist.length - 1]?.actIcon) this.loadSystemList();
				} else {
					if (this.multiples) {
						let index = this.value.findIndex(ite => ite.url == item.url);
						if (index >= 0) {
							if (this.value.length >= this.maxCount) return;
							this.value.splice(index, 1);
						} else {
							this.value.push(item);
						}
					} else {
						this.value = [item];
					}
					console.log(this.systemList);
				}
				console.log(this.value);
				this.$emit('selected', this.value);
			},
			jump(pathInfo) {
				// 处理路径导航点击，跳转到指定路径
				// 需要实现根据pathInfo.id或pathInfo.path加载对应目录
				this.currentParentId = pathInfo.id;
				// console.log(JSON.stringify(this.pathList), JSON.stringify(this.currentParentId));
				// 更新pathList，截断到点击的位置
				const index = this.pathList.findIndex(item => item.id == pathInfo.id);
				if (index !== -1) {
					this.pathList = this.pathList.slice(0, index + 1);
				}
				this.loadFileList(this.currentParentId);
			},
			formatFileSize(size) {
				// 格式化文件大小显示
				if (size === 0) return '0 B';
				const k = 1024;
				const sizes = ['B', 'KB', 'MB', 'GB'];
				const i = Math.floor(Math.log(size) / Math.log(k));
				return parseFloat((size / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
			}
		}
	};
</script>

<style scoped lang="scss">
	.document {
		// padding: 20rpx;

		.system {
			width: 100%;
			padding: 0px !important;


			.folder_item {
				padding: 2px 10px;
				display: flex;
				justify-content: space-between;
				align-items: center;
				border-top: 1px solid #EEEEEE;

				.system_item {
					display: flex;
					justify-content: flex-start;
					align-items: center;
					border: 1px solid #eee;
					padding: 2px 10px;
					border-radius: 5px;
				}
			}

			.folder_item:hover {
				background-color: #F0F9F7;
			}

			.folder_item:first-child {
				border-top: 0px;
			}

			.seted {
				background-color: #eee;
			}

			.btn {
				margin-left: 10px;
				cursor: pointer;
				font-size: 12px;
				/* display: flex;
					justify-content: space-between;
					align-items: center; */
				border-bottom: 1px solid rgba(0, 0, 0, 0);
			}

			.btn:hover {
				color: #409EFF;
				border-bottom: 1px solid #409EFF;
			}
		}

		.path-nav {
			margin-top: 5px;
			padding: 10rpx;
			font-size: 12px;
			border: 1px solid #eee;
			border-radius: 5px;
			display: flex;
			justify-content: space-between;
		}

		::v-deep .el-collapse-item__content {
			padding: 0px;
		}
	}
</style>